package com.hhkj.api.order.common.component.processor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hhkj.admin.order.common.cont.OrderConst;
import com.hhkj.admin.order.domain.Order;
import com.hhkj.admin.order.model.req.OrderReq;
import com.hhkj.admin.order.service.base.OrderService;
import com.hhkj.admin.order.service.biz.OrderBizService;
import com.hhkj.admin.order.service.extend.OrderExtendService;
import com.hhkj.payment.wechat.notification.common.processor.TransactionSuccessProcessor;
import com.ruoyi.common.exception.GlobalException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.model.TransactionAmount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * ApiOrderWechatPayCallBackProcessor
 * 订单支付回调处理器
 *
 * @author zheng
 * @since 2023/11/22 22:34
 */
@Slf4j
@Component
public class ApiOrderWechatPayTransactionSuccessProcessor implements TransactionSuccessProcessor {

    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private OrderBizService orderBizService;
    @Autowired
    private OrderService orderService;

    @Override
    public void process(Transaction transaction) {
        if (ObjectUtil.isEmpty(transaction)) {
            throw new GlobalException("信息读取失败！");
        }
        log.info(transaction.toString());
        // 3、修改并保存关联数据
        OrderReq orderReq = new OrderReq();
        Order orderPo = orderExtendService.getByNum(transaction.getOutTradeNo());
        orderReq.setId(orderPo.getId());
        orderReq.setPayMethodCode(OrderConst.PayMethodEnum.WECHAT.getCode());
        orderReq.setPayTime(DateUtil.parse(transaction.getSuccessTime()));
        orderReq.setTransactionId(transaction.getTransactionId());
        orderReq.setUpdateBy(orderPo.getSaleId());
        TransactionAmount transactionAmount = transaction.getAmount();
        String activeProfile = SpringUtil.getActiveProfile();
        BigDecimal payPrice;
        // 测试环境处理
        if ("pro".equals(activeProfile)) {
            payPrice = ObjectUtil.isEmpty(transactionAmount) ? BigDecimal.ZERO : new BigDecimal(transactionAmount.getTotal() / 100);
        } else {
            payPrice = orderPo.getPrice();
        }
        orderReq.setPayPrice(payPrice);
        try {
            orderBizService.validateAndPayOrder(orderReq, orderPo.getSaleId());
        } catch (Exception e) {
            // 异常情况，将对应订单信息设置为异常订单
            orderPo.setStatusCode(OrderConst.StatusEnum.ERROR.getCode());
            orderService.updateById(orderPo);
        }
    }
}
